﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ThreadSafe
{
    class Program
    {
        // private 防止类外去锁  static保证所有实例锁的是同一个 object表示引用类型
        private static readonly object Lock = new object();
        static void Main(string[] args)
        {
            int count = 0;
            List<Task> tasks = new List<Task>();
            Program program = new Program();
            List<int> list = new List<int>();
            for(int i=0;i<10000;i++)
            {
                int newI = i;
                tasks.Add(Task.Run(() =>
                {
                    lock (Lock)
                    {
                        count += 1;
                        list.Add(newI);
                    }
                }
                ));
            }

            Monitor.Enter(Lock);
            //中间是涉及共享资源的代码
            Monitor.Exit(Lock);

            Task.WaitAll(tasks.ToArray());
            Console.WriteLine(count);
            Console.WriteLine(list.Count);
        }
    }
}
